<template>
  <div class="statistics-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>统计查询</span>
      </div>
      <div class="filter-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange">
        </el-date-picker>
        <el-button type="primary" @click="fetchStatistics" :loading="loading">查询</el-button>
      </div>
    </el-card>

    <el-row :gutter="20" class="chart-container">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>废品回收统计表</span>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            v-loading="loading">
            <el-table-column
              prop="wasteTypeName"
              label="废品类型"
              width="180">
            </el-table-column>
            <el-table-column
              prop="quantity"
              label="回收重量">
              <template slot-scope="scope">
                {{ scope.row.quantity }} {{ scope.row.quantityUnit }}
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              label="总价格">
              <template slot-scope="scope">
                {{ scope.row.price }} 元
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>废品回收统计图</span>
          </div>
          <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'Statistics',
  data() {
    return {
      dateRange: [],
      loading: false,
      tableData: [],
      chart: null,
      wasteTypes: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
    this.fetchWasteTypes();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chartContainer) return;
      
      this.chart = echarts.init(this.$refs.chartContainer);
      this.chart.setOption({
        title: {
          text: '废品回收统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['回收重量', '总价格']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: [
          {
            type: 'value',
            name: '回收重量',
            position: 'left'
          },
          {
            type: 'value',
            name: '总价格(元)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '回收重量',
            type: 'bar',
            data: []
          },
          {
            name: '总价格',
            type: 'bar',
            yAxisIndex: 1,
            data: []
          }
        ]
      });

      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    async fetchWasteTypes() {
      try {
        const response = await this.$http.get('/zsd-waste/waste-type/selWasteType');
        if (response.data.code === 200) {
          this.wasteTypes = response.data.data;
        }
      } catch (error) {
        console.error('获取废品类型失败:', error);
        this.$message.error('获取废品类型失败');
      }
    },
    handleDateChange(val) {
      if (val) {
        this.dateRange = val;
      }
    },
    async fetchStatistics() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择日期范围');
        return;
      }

      this.loading = true;
      try {
        const [startDate, endDate] = this.dateRange;
        const response = await this.$http.get('/zsd-order/statistics/statistics', {
          params: {
            startDate,
            endDate
          }
        });

        if (response.data.code === 200) {
          this.tableData = response.data.data;
          this.updateChart();
        } else {
          this.$message.error(response.data.msg || '获取统计数据失败');
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      } finally {
        this.loading = false;
      }
    },
    updateChart() {
      if (!this.chart) return;

      const xAxisData = this.tableData.map(item => item.wasteTypeName);
      const quantityData = this.tableData.map(item => item.quantity);
      const priceData = this.tableData.map(item => item.price);

      this.chart.setOption({
        xAxis: {
          data: xAxisData
        },
        series: [
          {
            data: quantityData
          },
          {
            data: priceData
          }
        ]
      });
    }
  }
};
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.chart-container {
  margin-top: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.el-date-picker {
  margin-right: 10px;
}
</style>
